package com.haifeng.wdsh.auth.impl;


import com.haifeng.wdsh.common.base.exception.ErrorMsg;
import com.haifeng.wdsh.common.base.util.JsonUtil;
import com.haifeng.wdsh.common.base.util.Rest;
import com.haifeng.wdsh.common.base.vo.PermissionVo;
import com.haifeng.wdsh.common.base.vo.UserVo;
import com.haifeng.wdsh.api.sys.service.UserService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;

/**
 * <p>
 *  自定义UserDetailsService
 * </p>
 *
 * @author: Haifeng
 * @date: 2020-05-06
 */
@Slf4j
@Service
@AllArgsConstructor
public class UserDetailsServiceImpl implements UserDetailsService {

    private final UserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        //根据用户名查询出用户信息及权限信息，涉及到密码，直接查数据库
        Rest<UserVo> rest = userService.getUserByUsername(username);
        if (!rest.getSuccess()){
            log.warn("查询用户["+username+"]信息及权限出错: "+ rest.getMessage());
            throw new UsernameNotFoundException("查询用户["+username+"]信息及权限出错: "+ rest.getMessage());
        }
        UserVo user = rest.getData();
        if (user == null) {
            log.warn("[UserDetailsServiceImpl]用户不存在: "+ username);
            throw new UsernameNotFoundException(String.format(ErrorMsg.USER_NOT_FOUND,username));
        }
        // 或者让实体实现UserDetailsService
        String password = user.getPassword();
        // JWT信息只包含用户名和权限信息
        Map map = new HashMap<>(16);
        map.put("username",user.getUsername());
        map.put("permissions",user.getPermissions());
        String uname = JsonUtil.toJsonString(map);
        boolean enabled = user.getEnabled();
        boolean accountNonExpired = user.getAccountNonExpired();
        boolean credentialsNonExpired = user.getCredentialsNonExpired();
        boolean accountNonLocked = user.getAccountNonLocked();
        Collection<? extends GrantedAuthority > authorities = getAuthorities(user.getPermissions());
        return new org.springframework.security.core.userdetails.User(
                uname,password,enabled,accountNonExpired,credentialsNonExpired,accountNonLocked,authorities);
    }

    public Collection<? extends GrantedAuthority> getAuthorities(Set<PermissionVo> permissions){
        List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
        if (!CollectionUtils.isEmpty(permissions)) {
            permissions.forEach(permissionDto -> {
                if (permissionDto != null && permissionDto.getPermissionCode() != null) {
                    GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(permissionDto.getPermissionCode());
                    grantedAuthorities.add(grantedAuthority);
                }
            });
        }
        return grantedAuthorities;
    }
}
